package com.javacoo.xservice.example.service.impl;

import java.util.Optional;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.javacoo.xservice.base.support.AbstractAssert;
import com.javacoo.xservice.base.utils.CacheUtil;
import com.javacoo.xservice.example.bean.dto.ExampleDto;
import com.javacoo.xservice.example.constant.ErrorCodeConstants;
import com.javacoo.xservice.example.dao.ExampleDao;
import com.javacoo.xservice.example.service.ExampleService;

import lombok.extern.slf4j.Slf4j;

/**
 * 案例数据服务接口实现
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年7月14日下午1:30:18
 */
@Service
@Slf4j
public class ExampleServiceImpl implements ExampleService {
    /**
     * 查询缓存KEY:id
     */
    private static final String QUERY_CACHE_KEY = "query:%1$s";
    /**
     * 查询缓存超时时间:1 分钟
     */
    private static final int QUERY_CACHE_TIMEOUT = 60 * 1;
    /**
     * 缓存工具类
     */
    @Autowired
    protected CacheUtil cacheUtil;
	@Autowired
    private ExampleDao exampleDao;

	@Override
	public Optional<ExampleDto> getExampleInfo(String id) {
		AbstractAssert.isNotBlank(id, ErrorCodeConstants.SERVICE_GET_EXAMPLE_INFO_ID);
        // ExampleDto exampleDto = new ExampleDto();
        // exampleDto.setData("这是测试数据");
        // exampleDto.setId("1");
        // 从缓存中获取数据
        String cacheKey = String.format(QUERY_CACHE_KEY,id);
        return Optional.ofNullable(cacheUtil.getCacheValueFunction(cacheKey,QUERY_CACHE_TIMEOUT,ExampleDto.class, getExampleInfoFunction,id));
	}

    /**
     * 获取示例信息函数
     * <li></li>
     * @author duanyong@jccfc.com
     * @date 2021/7/14 16:39
     * @param id: id
     * @return: ExampleDto 示例信息
     */
    private Function<String, ExampleDto> getExampleInfoFunction = (String id)-> exampleDao.getExampleInfo(id);

}
